package com.ford.microservices.services.web;

import com.ford.microservices.common.AccountDto;
import com.ford.microservices.common.SignUpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.logging.Logger;

/**
 * Hide the access to the microservice inside this local service.
 */
@Service
public class WebAccountsService {

    @Autowired
    @LoadBalanced
    protected RestTemplate restTemplate;

    protected String serviceUrl;

    protected Logger logger = Logger.getLogger(WebAccountsService.class.getName());

    public WebAccountsService(String serviceUrl) {
        this.serviceUrl = serviceUrl.startsWith("http") ? serviceUrl : "http://" + serviceUrl;
    }

    public AccountDto findById(Long id) {
        logger.info("findById() invoked: for " + id);
        return restTemplate.getForObject(serviceUrl + "/accounts/{id}", AccountDto.class, id);
    }

    public AccountDto findByCellPhone(String cellPhone) {
        logger.info("findByCellPhone() invoked: for " + cellPhone);
        return restTemplate.getForObject(serviceUrl + "/accounts/query/{cellPhone}", AccountDto.class, cellPhone);
    }

    public SignUpResponse singUp(AccountDto signUpDto) {
        logger.info("singUp() invoked: for " + signUpDto);
        return restTemplate.postForObject(serviceUrl + "/signUp", signUpDto, SignUpResponse.class);
    }

    public ResponseEntity<String> checkIn(Long id) {
        logger.info("checkIn() invoked: for " + id);
        ResponseEntity<String> response = restTemplate.getForEntity(serviceUrl + "/checkin/{id}", String.class, id);
        return response;
    }

    public ResponseEntity<AccountDto[]> report() {
        logger.info("report() invoked: for ");
        return restTemplate.getForEntity(serviceUrl + "/sales", AccountDto[].class);
    }
}
